package com.lxk.util;

import com.lxk.config.UrlConfig;
import com.lxk.util.exception.GlobalException;
import com.lxk.vo.result.CodeMsg;
import org.apache.commons.io.FileUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

/**
 * @author JohnSoybean
 * @create 2020/6/17 15:56
 * @description 文件处理工具类
 */
public class MyFileUtil {

    /**
     * 图片根目录路径
     */
    public static final String parentPath = UrlConfig.SERVER_ADDRESS + "/img/";

    /**
     * CFG 图片根目录路径
     */
    public static final String parentUrl = UrlConfig.FRONT_URL + "/img/";

    /**
     * 获取文件后缀名
     *
     * @param file
     * @return
     */
    public static String getSuffix(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        return suffix;
    }

    /**
     * 判断是否为图片
     *
     * @param suffix
     * @return
     */
    public static boolean isImage(String suffix) {
        if (suffix.equalsIgnoreCase(".png") ||
                suffix.equalsIgnoreCase(".jpg") ||
                suffix.equalsIgnoreCase(".jpeg") ||
                suffix.equalsIgnoreCase(".bmp")) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 生成随机文件名
     *
     * @param suffix
     * @return
     */
    public static String randomFileName(String suffix) {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String filePath = uuid + suffix;
        return filePath;
    }

    /**
     * 上传图片
     * @param file
     * @return
     */
    public static String uploadImage(MultipartFile file) {
        if(file==null) {
            throw new GlobalException(CodeMsg.FILE_NOT_EXIST);
        }
        String suffix = getSuffix(file);
        if(isImage(suffix)) {
            File parent = new File(parentPath);
            String filePath = randomFileName(suffix);
            try {
                File trueFile = new File(parent, filePath);
                FileUtils.copyInputStreamToFile(file.getInputStream(), trueFile);
                System.out.println("下载媒体文件成功");
                //更改权限
                changeFolderPermission(trueFile);
                return parentUrl + filePath;
            } catch (IOException e) {
                e.printStackTrace();
                throw new GlobalException(CodeMsg.FILE_UPLOAD_FAIL);
            }
        } else {
            throw new GlobalException(CodeMsg.FILE_UPLOAD_FAIL);
        }
    }

    /**
     * 上传图片 本地测试环境
     * @param file
     * @return
     */
    public static String uploadImageDev(MultipartFile file) {
        if(file==null) {
            throw new GlobalException(CodeMsg.FILE_NOT_EXIST);
        }
        String suffix = getSuffix(file);
        if(isImage(suffix)) {
            String url = null;
            try {
                url = ResourceUtils.getURL("classpath:static").getPath() + "/img/";
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            File parent = new File(url);
            String fileName = randomFileName(suffix);
            try {
                File trueFile = new File(parent, fileName);
                FileUtils.copyInputStreamToFile(file.getInputStream(), trueFile);
                System.out.println("下载媒体文件成功");
                //更改权限
//                changeFolderPermission(trueFile);
                return parentUrl + fileName;
            } catch (IOException e) {
                e.printStackTrace();
                throw new GlobalException(CodeMsg.FILE_UPLOAD_FAIL);
            }
        } else {
            throw new GlobalException(CodeMsg.FILE_TYPE_ERROR);
        }
    }

    /**
     * 上传普通文件
     * @param file
     * @return
     */
    public static String uploadFile(MultipartFile file) {
        if(file==null) {
            throw new GlobalException(CodeMsg.FILE_NOT_EXIST);
        }
        String suffix = getSuffix(file);
        File parent = new File(parentPath);
        String filePath = randomFileName(suffix);
        try {
            File trueFile = new File(parent, filePath);
            FileUtils.copyInputStreamToFile(file.getInputStream(), trueFile);
            System.out.println("下载文件成功");
            changeFolderPermission(trueFile);
            return parentUrl + filePath;
        } catch (IOException e) {
            e.printStackTrace();
            throw new GlobalException(CodeMsg.FILE_UPLOAD_FAIL);
        }
    }

    /**
     * 设置文件权限 777
     * @param dirFile
     * @throws IOException
     */
    public static void changeFolderPermission(File dirFile) throws IOException {
        Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
        perms.add(PosixFilePermission.OWNER_READ);
        perms.add(PosixFilePermission.OWNER_WRITE);
        perms.add(PosixFilePermission.OWNER_EXECUTE);
        perms.add(PosixFilePermission.GROUP_READ);
        perms.add(PosixFilePermission.GROUP_WRITE);
        perms.add(PosixFilePermission.GROUP_EXECUTE);
        perms.add(PosixFilePermission.OTHERS_EXECUTE);
        perms.add(PosixFilePermission.OTHERS_READ);
        perms.add(PosixFilePermission.OTHERS_WRITE);
        try {
            Path path = Paths.get(dirFile.getAbsolutePath());
            System.out.println(dirFile.getAbsolutePath());
            Files.setPosixFilePermissions(path, perms);
        } catch (Exception e) {
            System.out.println("更改权限失败");
            System.out.println(e);
        }
    }

}
